<template>
  <div class="pdfBody">
    <div
      v-loading="loading"
      class="content"
      :style="{height: height+'px'}"
      :element-loading-text="loadTxt"
    >
      <div class="fileList">
        <el-card>
          <el-row slot="header">
            <el-col :span="12">签名文件列表</el-col>
            <el-col :span="12" style="text-align: right;">
              <el-button size="mini" type="success" @click="addFile">新增文件</el-button>
            </el-col>
          </el-row>
          <div class="signFileList" :style="{ height: (height - 130)+ 'px'}">
            <div v-for="item in signFiles" :key="item.Id" :class="'signFile' + (curFile != null && item.Id == curFile.Id ? ' active': '')" @click="accredit(item)">
              <img v-if="item.ImgUri" :src="item.ImgUri | imageUri" :alt="item.FileName">
              <img v-else src="/image/pdf.png">
              <el-link type="danger" class="drop" icon="el-icon-delete" @click="dropSign(item)" />
              <div class="title" :title="item.FileName">{{ item.FileName }}</div>
            </div>
          </div>
        </el-card>
      </div>
      <div class="pdfFile">
        <el-row class="btnList">
          <el-col :span="6" style="text-align: left;">
            <el-link v-if="isShowMenu" :icon="menuVisible? 'el-icon-s-fold' :'el-icon-s-unfold'" @click="openMenu" />
            <el-divider direction="vertical" style="width: 2px;" />{{ fileName }}
          </el-col>
          <el-col :span="12" style="text-align: center;">
            <el-pagination
              v-if="isNull == false"
              :current-page="index"
              :page-size="1"
              layout="total, prev, pager, next, jumper"
              :total="numPages"
              @current-change="pagingChange"
            />
            <span v-else style="display: inline-flex;" />
          </el-col>
          <el-col :span="6" style="text-align: right;">
            <el-button :disabled="isNull" type="primary" @click="addSignaturen">添加签章</el-button>
            <el-button :disabled="isNull" type="primary" @click="addSign">添加签名</el-button>
            <el-button :disabled="isNull" type="success" @click="save">保存</el-button>
          </el-col>
        </el-row>
        <div class="body">
          <pdf v-if="isNull == false" id="pdfDiv" ref="pdfFile" :key="index" :src="uri" :page="index" @loaded="pdfLoaded" @progress="refreshProgress" />
          <el-empty v-else description="请选择或添加签名文件" />
          <VueDragResize
            v-for="item in signList"
            :key="item.Id"
            :aspect-ratio="true"
            :parent-limitation="false"
            :is-active="true"
            :y="item.top"
            :x="item.left"
            :w="item.width"
            :z="9"
            :h="item.height"
            :minw="80"
            :minh="80"
            @resizing="(e)=>resize(e,item)"
            @dragging="(e)=>resize(e,item)"
          >
            <img style="width: 100%;height:100%" :src="item.FileUri |imageUri">
            <el-link type="danger" class="drop" icon="el-icon-delete" @click="drop(item)" />
          </VueDragResize>
        </div>
      </div>
    </div>
    <flowFileList style="text-align: left;" :log-id="logId" :item-id="itemId" :visible.sync="visible" @save="saveFile" />
    <el-drawer
      title="目录"
      size="400px;"
      :visible.sync="menuVisible"
      :modal="false"
      direction="ltr"
    >
      <el-tree
        :data="menus"
        :default-expanded-keys="menuKeys"
        :default-expand-all="true"
        node-key="id"
        @node-click="chioseMenu"
      />
    </el-drawer>
    <pdfSignEdit :accredit-id.sync="accreditId" :visible.sync="signVisible" @save="add" />
    <pdfSignatureEdit :accredit-id.sync="accreditId" :visible.sync="signatureVisible" @save="add" />
  </div>
</template>

<script>
import pdf from 'vue-pdf'
import VueDragResize from 'vue-drag-resize'
import * as signFileApi from '@/flow/api/signFile'
import { copy, upFileStream, getfileUpUri } from '@/api/base/file'
import flowFileList from './flowFileList.vue'
import * as pdfApi from '@/api/file/pdfFile'
import { PdfSign } from '@/api/emp/empSign'
import pdfSignEdit from './pdfSignEdit.vue'
import pdfSignatureEdit from './pdfSignatureEdit.vue'
export default {
  components: {
    pdf,
    VueDragResize,
    flowFileList,
    pdfSignEdit,
    pdfSignatureEdit
  },
  props: {
    logId: {
      type: String,
      default: null
    },
    itemId: {
      type: String,
      default: null
    },
    isLoad: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      numPages: 1,
      index: 1,
      loading: false,
      uri: null,
      curFile: null,
      loadTxt: 'PDF加载中....',
      fileName: null,
      isShowMenu: false,
      menuKeys: [],
      menuVisible: false,
      signVisible: false,
      menuId: 1,
      signatureVisible: false,
      accreditId: null,
      visible: false,
      isNull: false,
      height: 1820,
      signFiles: [],
      pageSign: {},
      signList: [],
      pdf: null,
      menus: [],
      isInit: false,
      page: {
        width: 0,
        height: 0
      }
    }
  },
  computed: {
    mainHeight() {
      return this.$store.getters.mainHeight
    }
  },
  watch: {
    isLoad: {
      handler(val) {
        if (val) {
          this.$nextTick(this.loadFile)
        }
      },
      immediate: true
    }
  },
  mounted() {

  },
  methods: {
    addFile() {
      this.visible = true
    },
    dropSign(item) {
      const title = '确认删除文件 ' + item.FileName + '?'
      const that = this
      this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.submitDrop(item.Id)
      })
    },
    async submitDrop(id) {
      await signFileApi.Delete(id)
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
      this.loadFile()
    },
    async save() {
      if (this.signList.length === 0) {
        this.$message({
          type: 'error',
          message: '签名文件不能为空!'
        })
        return
      }
      const title = '确认保存签名后的PDF文件?'
      const that = this
      this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.saveSign()
      })
    },
    async saveSign() {
      const res = await PdfSign(this.accreditId, {
        Width: this.page.width,
        Height: this.page.height,
        PdfFileId: this.curFile.FileId,
        LinkBizPk: this.logId,
        DirKey: 'PdfFileDir',
        Tag: null,
        Sign: this.signList.map(c => {
          return {
            Index: c.index,
            SignFileId: c.SignId,
            FileId: c.FileId,
            Width: c.width,
            Height: c.height,
            X: c.left,
            Y: c.top,
            Reason: c.Reason,
            Location: c.Location
          }
        })
      })
      this.addLog(res)
    },
    async addLog(file) {
      const add = {
        LogId: this.logId,
        SignFileId: this.curFile.Id,
        SourceFileId: this.curFile.FileId,
        FileId: file.FileId,
        FileUri: file.FileUri,
        SignItemId: this.itemId,
        Items: this.signList.map(c => {
          return {
            CertFileId: c.SignId,
            SignImgFileId: c.FileId,
            SignType: c.SignType,
            Reason: c.Reason,
            Location: c.Location
          }
        })
      }
      await signFileApi.AddLog(add)
      this.curFile.FileId = file.FileId
      this.curFile.FileUri = file.FileUri
      this.load(this.curFile)
    },
    openMenu() {
      this.menuVisible = true
    },
    refreshProgress(num) {
      this.loadTxt = '加载中，进度：' + Math.ceil(num * 100) + '%'
    },
    async accredit(file) {
      await signFileApi.Accredit(this.logId, file.Id)
      this.load(file)
    },
    async load(file) {
      this.index = 1
      this.curFile = file
      this.isInit = false
      this.pageSign = {}
      this.pageSign[this.index] = []
      this.signList = []
      this.uri = file.FileUri + '?accreditId=' + this.$store.getters.token
      this.fileName = file.FileName
    },
    resize(e, item) {
      item.top = e.top
      item.left = e.left
      item.width = e.width
      item.height = e.height
    },
    pagingChange(index) {
      if (this.pageSign[index] == null) {
        this.pageSign[index] = []
      }
      this.signList = this.pageSign[index]
      this.index = index
    },
    addSign() {
      this.signVisible = true
    },
    addSignaturen() {
      this.signatureVisible = true
    },
    drop(sign) {
      const list = this.pageSign[this.index]
      const index = list.findIndex(c => c.Id === sign.Id)
      list.splice(index, 1)
    },
    add(sign) {
      const list = this.pageSign[this.index]
      list.push({
        Id: 'a_' + this.id,
        left: 0,
        index: this.index,
        SignId: sign.SignId,
        FileId: sign.FileId,
        FileUri: sign.FileUri,
        SignType: sign.SignType,
        top: 0,
        width: sign.Width,
        height: sign.Height
      })
      this.signList = list
      this.id = this.id + 1
    },
    pdfLoaded(e, control) {
      this.pdf = e
      if (this.isInit === false && e != null) {
        this.isInit = true
        this.numPages = this.pdf.numPages
        this.pdf.getOutline().then(e => {
          if (e != null) {
            this.isShowMenu = true
            this.menuKeys = []
            this.menus = e.map(c => this.loadMenu(c))
          } else {
            this.isShowMenu = false
          }
        })
        this.page = {
          width: this.$refs.pdfFile.$el.clientWidth,
          height: this.$refs.pdfFile.$el.clientHeight
        }
        if (this.curFile.ImgUri == null || this.curFile.ImgUri === '') {
          const that = this
          window.setTimeout(() => {
            that.upPdfImg(control)
          }, 2000)
        }
      }
      this.loading = false
    },
    async upPdfImg(control) {
      const uri = getfileUpUri('FlowSignCoverImg')
      const baseurl = control.toDataURL('image/png')
      const res = await upFileStream(uri, this.dataURLtoBlob(baseurl), 'signIndex.png', null)
      this.saveImg(res)
    },
    async saveImg(file) {
      await signFileApi.SetImgUri(this.curFile.Id, {
        FileId: file.FileId,
        FileUri: file.FileUri
      })
      this.curFile.ImgUri = file.FileUri
    },
    dataURLtoBlob(baseurl) {
      var arr = baseurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    loadMenu(data) {
      const menu = {
        id: this.menuId,
        label: data.title,
        dest: data.dest[0],
        children: null
      }
      if (data.items.length > 0) {
        this.menuKeys.push(menu.id)
        menu.children = data.items.map(c => {
          return this.loadMenu(c)
        })
      }
      this.menuId = this.menuId + 1
      return menu
    },
    async chioseMenu(e) {
      this.index = await this.pdf.getPageIndex(e.dest) + 1
    },
    saveFile(file) {
      this.loading = true
      if (file.Extension === '.pdf') {
        this.loadTxt = '文件添加中!'
        this.copyFile(file)
      } else {
        this.loadTxt = '正在将文件转换为PDF文件，请稍后!'
        this.convertPdf(file)
      }
    },
    async copyFile(file) {
      const res = await copy({
        FileId: file.FileId,
        DirKey: 'PdfFileDir',
        LinkBizPk: this.logId
      })
      this.addSignFile(res, file)
    },
    async addSignFile(res, file) {
      const id = await signFileApi.Add({
        LogId: this.logId,
        ItemId: this.itemId,
        FormFileId: file.FileId,
        FileId: res.FileId,
        FileUri: res.FileUri,
        FileName: res.FileName
      })
      const add = {
        Id: id,
        FileId: res.FileId,
        FileUri: res.FileUri,
        FileName: res.FileName,
        ImgUri: null
      }
      this.signFiles.push(add)
      this.isNull = false
      this.load(add)
    },
    async convertPdf(file) {
      const res = await pdfApi.Convert({
        FileId: file.FileId,
        LinkBizPk: this.linkBizPk,
        DirKey: 'PdfFileDir'
      })
      if (res.IsComplete) {
        this.loadTxt = '转换完成,正在加载...'
        this.addSignFile(res.File, file)
      } else {
        const that = this
        window.setTimeout(function() {
          that.checkResult(res.TaskId, file)
        }, 1000)
      }
    },
    async checkResult(taskId, file) {
      const res = await pdfApi.Get(taskId)
      if (res.IsComplete) {
        this.loadTxt = '转换完成,正在加载...'
        this.addSignFile(res.File, file)
      } else {
        const that = this
        window.setTimeout(function() {
          that.checkResult(res.TaskId, file)
        }, 1000)
      }
    },
    async loadFile() {
      this.loading = false
      this.loadTxt = '文件加载中,请稍后...'
      this.fileName = null
      const res = await signFileApi.Gets(this.logId)
      this.signFiles = res
      if (res.length > 0) {
        this.load(res[0])
        this.isNull = false
      } else {
        this.isNull = true
      }
      this.loading = false
    }
  }
}
</script>
<style scoped>
.pdfBody {
    width: 100%;
    text-align: center;
}
.pdfBody .content {
    width: 1600px;
    display: inline-flex;
    margin-right: 10px;
}
.content .fileList {
    width: auto;
    float: left;
    width: 300px;
}
.content .fileList .fileBody {
    overflow-x: hidden;
    overflow-y: auto;
}
.content .pdfFile {
    width: 1240px;
    height: 1800px;
    float: left;
    margin-left: 10px;
}
.content .pdfFile .body {
  width: 100%;
  position: relative;
  z-index: 99;
}
.content .pdfFile .btnList{
  height: 30px;
  line-height: 30px;
  margin-bottom: 10px;
}
.signFileList {
    width: 100%;
    text-align: center;
    overflow-x: hidden;
    overflow-y: auto;
}
.signFileList .signFile{
   width: 200px;
   height: 282px;
   position: relative;
   cursor: pointer;
   display: inline-flex;
   margin-bottom: 10px;
}
.signFileList .signFile .drop{
    position: absolute;
    right: -20px;
    font-size: 15px;
    cursor: pointer;
}
.signFileList .active {
    border: 1px solid #ff4949;
}
.signFileList .signFile img{
   width: 100%;
   height: 100%;
}
.signFileList .signFile .title{
   width: 200px;
    display: inline-block;
    height: 30px;
    line-height: 30px;
    position: absolute;
    z-index: 1;
    left: 0;
    bottom: 0;
    background-color: #414243a1;
    font-size: 14px;
    overflow: hidden;
}
.content .pdfFile .body .drop{
    position: absolute;
    right: -20px;
    font-size: 15px;
    cursor: pointer;
}

</style>
